<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace extend\kdniao\request;

use builder\helper\Url;
use extend\kdniao\BaseRequest;
use extend\kdniao\Kdniao;
use yii\base\UserException;
use yii\helpers\Json;

/**
 * 物流轨迹订阅发布
 * ```php
 * //创建物流轨迹订阅服务实例
 * $trackSubscribeRequest = TrackSubscribeRequest::createObject();
 * $trackSubscribeRequest->setCustomParams(['platform' => 'Wx_3c_Shop'])
 *      ->setNotifyUrl('https://www.notify.com/notify')
 *      ->setParamOrderCode('XS54568222222135500000')
 *      ->setParamShipperCode('SF')
 *      ->setParamLogisticCode('SF8880241669912')
 *      ->setParamCustomerName('1196');
 *
 * //创建快递鸟客户端
 * $kdniao = Kdniao::createObject();
 * $execState = $kdniao->setRequest($trackSubscribeRequest)->execute();
 * if ($execState) {
 *     return $kdniao->result;
 * } else {
 *     return $kdniao->error;
 * }
 *
 * ```
 * @author clevstn
 * @since ym2.0
 */
class TrackSubscribeRequest extends BaseRequest
{
    //服务请求标识
    private $_requestUri = 'api/dist';
    //服务指令标识
    private $_requestType = '8008';
    //请求内容需进行URL(utf-8)编码。请求内容JSON格式，须和DataType一致。
    private $_requestData = [];
    //请求、返回数据类型：2-json；
    private $_dataType = '2';

    /**
     * @param string $notifyUrl 订阅回传URL
     * @return $this
     * @throws UserException
     */
    public function setNotifyUrl($notifyUrl)
    {
        if (Url::isRelative($notifyUrl)) {
            throw new UserException('物流轨迹订阅回调URL非法。');
        }

        $this->_requestData['CallbackUrl'] = $notifyUrl;
        return $this;
    }

    /**
     * @param array $params 自定义参数
     * @return $this
     */
    public function setCustomParams(array $params)
    {
        $this->_requestData['CallBack'] = Json::encode($params);
        return $this;
    }

    /**
     * @param string $businessOrderNo 商家订单号
     * @return $this
     */
    public function setParamOrderCode($businessOrderNo)
    {
        $this->_requestData['OrderCode'] = $businessOrderNo;
        return $this;
    }

    /**
     * @param string $shipperCode 快递公司编码
     * @return $this
     */
    public function setParamShipperCode($shipperCode)
    {
        $this->_requestData['ShipperCode'] = $shipperCode;
        return $this;
    }

    /**
     * @param string $logisticCode 快递单号
     * @return $this
     */
    public function setParamLogisticCode($logisticCode)
    {
        $this->_requestData['LogisticCode'] = $logisticCode;
        return $this;
    }

    /**
     * @param string $mobileLastFour
     * 顺丰必填
     * 寄件人or收件人 手机号后四位
     * 虚拟号后四位不可用
     * 后四位传值错误无法获取到顺丰轨迹（可能拉取缓存）
     * 后四位正确性可通过微信小程序【顺丰速运+】验证
     * @return $this
     */
    public function setParamCustomerName($mobileLastFour)
    {
        $this->_requestData['CustomerName'] = $mobileLastFour;
        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function getRequestUrl()
    {
        return self::API_DOMAIN . $this->_requestUri;
    }

    /**
     * {@inheritDoc}
     */
    public function getServiceName()
    {
        return '物流轨迹订阅';
    }

    /**
     * {@inheritDoc}
     */
    public function getRequestParams()
    {
        $requestData = Json::encode($this->_requestData);
        return [
            'EBusinessID' => Kdniao::E_BUSINESS_ID,
            'RequestType' => $this->_requestType,
            'RequestData' => urlencode($requestData),
            'DataType' => $this->_dataType,
            'DataSign' => Kdniao::generateSign($requestData),
        ];
    }

    /**
     * {@inheritDoc}
     */
    public function triggerResponseCallback(Kdniao $kdniao)
    {
        if (!$kdniao->hasError()) {
            try {
                $result = Json::decode($kdniao->result);
                $kdniao->result = $result;
            } catch (\Throwable $e) {
                $kdniao->error = $e->getMessage();
            }
        }
    }
}